package o2o.web.actions.agent;

import o2o.config.dao.UserDaoSql;
import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ObjectUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.agent.AgentOrderOverTimeMemory;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.agent.OrderOverTimeInfo;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.agent.OrderOverTimeInfoVO;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderOverTimeAction {

    // 获取商圈配置信息
    @RequestMapping(value = "agent/order/overtime/info")
    public String agent_order_overtime_get(String token, Long agentId) {
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        }
        boolean hasCityAuth = false;
        if (!ValidateUtil.isAbsLong(agentId)) {
            return AjaxResult.errorResult("商圈id不能为空");
        }
        CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
        if (cityAgent == null) {
            return AjaxResult.errorResult("商圈信息不存在，请核实");
        }
        if (user != null) {
            // 普通用户还是超级管理的
            if (User.hasCityAuth(user.getUsername(), cityAgent.getCity(), user.getUserType())) {
                hasCityAuth = true;
            }
        }
        OrderOverTimeInfo info = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(agentId);
        if (info == null) {
            // 添加和获取
            if (hasCityAuth) {
                ResultInfo resultInfo = CityAgentMan.copyPlateSettingForAgent(agentId, user.getUsername());
                if (resultInfo == null) {
                    return AjaxResult.errorResult("获取失败，请稍重试");
                }
                if (!resultInfo.isSuccess()) {
                    return AjaxResult.errorResult(resultInfo.getError());
                }
                info = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(agentId);
            } else {
                info = AgentOrderOverTimeMemory.getInstance().getPlateDefaultSetting();
            }
        }
        if (info == null) {
            return AjaxResult.errorResult("获取配置设置，请稍后重试");
        }
        // OrderOverTimeInfoVO infoVO = new OrderOverTimeInfoVO();
        // try {
        //     ObjectUtils.copyPropertiesExclude(info, infoVO);
        // } catch (Exception e) {
        //     e.printStackTrace();
        //     return AjaxResult.errorResult("获取商圈配置错误，请稍后重试");
        // }
        return AjaxResult.successResult(info);
    }

    // 添加 修改 获取 删除
    @RequestMapping(value = "agent/order/overtime/modifyOrAdd")
    public String agent_order_overtime_add_modify(String token, OrderOverTimeInfo info) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!ValidateUtil.isAbsLong(info.getAgentId())) {
            return AjaxResult.errorResult("商圈id不能为空");
        }
        CityAgent cityAgent = CityAgentMemory.getInstance().getById(info.getAgentId());
        if (cityAgent == null) {
            return AjaxResult.errorResult("商圈信息不存在，请核实");
        }
        if (!User.hasCityAuth(user.getUsername(), cityAgent.getCity(), user.getUserType())) {
            return AjaxResult.errorResult("你没有操作权限");
        }
//        if (ValidateUtil.isNotAbsInteger(info.getPostmanOverTime())) {
//            return AjaxResult.errorResult("订单配送时间不能为空");
//        }
//        if (ValidateUtil.isNotAbsInteger(info.getAlertPostmanTime())) {
//            return AjaxResult.errorResult("订单超时提醒时间不能为空");
//        }
        // 店铺的


        // 根据商圈获取设置信息
        // 获取设置
        OrderOverTimeInfo infoDB = AgentOrderOverTimeMemory.getInstance().getAgentOrderOverTimeInfoByAgentId(info.getAgentId());
        if (infoDB == null) {
            if (ValidateUtil.isNotAbsInteger(info.getPostmanOverTime())) {
                info.setPostmanOverTime(0);
            }
            // 骑手提前送达时间
            if (ValidateUtil.isNotAbsInteger(info.getAlertPostmanTime())) {
                info.setAlertPostmanTime(0);
            }
            if (ValidateUtil.isNotAbsInteger(info.getPostmanAdvanceTime())) {
                return AjaxResult.errorResult("骑手提前送达时间不能为空");
            }
            if (info.getShopOverTime() == null) {
                info.setShopOverTime(0);
            }
            if (info.getAlertShopTime() == null) {
                info.setAlertShopTime(0);
            }
            // 订单的
            if (ValidateUtil.isNotAbsInteger(info.getFixedOrderPsTime())) {
                info.setFixedOrderPsTime(0);
            }
            if (ValidateUtil.isNotAbsDouble(info.getWithPsKmInRang())) {
                info.setWithPsKmInRang(0.0d);
            }
            if (ValidateUtil.isNotAbsInteger(info.getOutOneKmTime())) {
                info.setOutOneKmTime(0);
            }
            if (SYS_SETTINGS.DELIVERY_TIME_BY_DISTANCE != null && SYS_SETTINGS.DELIVERY_TIME_BY_DISTANCE == 1) {
                if (ValidateUtil.isNotAbsInteger(info.getOrderOverTime())) {
                    info.setOrderOverTime(info.getFixedOrderPsTime());
                }
            } else {
                if (ValidateUtil.isNotAbsInteger(info.getOrderOverTime())) {
                    info.setOrderOverTime(0);
                }
            }
            if (ValidateUtil.isNotAbsInteger(info.getAlertOrderTime())) {
                info.setAlertOrderTime(0);
            }
            // 骑手接单未取货时间
            if (ValidateUtil.isNotAbsInteger(info.getNotTakenOrderTime())) {
                info.setNotTakenOrderTime(0);
            }
            if (ValidateUtil.isNotAbsInteger(info.getPostmanAdvanceTime())) {
                info.setPostmanAdvanceTime(0);
            }
            if (ValidateUtil.isNotAbsInteger(info.getPostmanBackOrderTime())) {
                info.setPostmanBackOrderTime(0);
            }
            if (StringUtils.isEmpty(info.getDeliveryType())) {
                info.setDeliveryType("sys");        // 默认非第三方配送
            }
            // 插入
            long cTime = DateUtils.getCurrTime();
            info.setCreateTime(cTime).setCreateUser(user.getUsername());
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.AGENT_ORDER_OVERTIME, info);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("添加失败，请稍重试");
            }
            AgentOrderOverTimeMemory.getInstance().add(cTime);
        } else {
            // 更新
            StringBuffer sql = new StringBuffer();
            boolean isUpdate = false;
            String postmanOverTime = "";
            if (ValidateUtil.isAbsInteger(info.getPostmanOverTime())) {
                postmanOverTime = ",postmanOverTime=" + info.getPostmanOverTime();
                isUpdate = true;
            }
            String isOpen = "";
            if (ValidateUtil.isAbsInteger(info.getIsOpen())) {
                isOpen = ",isOpen=" + info.getIsOpen();
                isUpdate = true;
            }
            String alertPostmanTime = "";
            if (ValidateUtil.isAbsInteger(info.getAlertPostmanTime())) {
                alertPostmanTime = ", alertPostmanTime = " + info.getAlertPostmanTime();
                isUpdate = true;
            }
            String shopOverTime = "";
            if (ValidateUtil.isAbsInteger(info.getShopOverTime())) {
                shopOverTime = ", shopOverTime = " + info.getShopOverTime();
                isUpdate = true;
            }
            String alertShopTime = "";
            if (ValidateUtil.isAbsInteger(info.getAlertShopTime())) {
                alertShopTime = ", alertShopTime = " + info.getAlertShopTime();
                isUpdate = true;
            }
            String orderOverTime = "";
            if (ValidateUtil.isAbsInteger(info.getOrderOverTime())) {
                orderOverTime = ", orderOverTime =" + info.getOrderOverTime();
                isUpdate = true;
            }

            if (ValidateUtil.isAbsInteger(info.getFixedOrderPsTime())) {
                orderOverTime += ", fixedOrderPsTime =" + info.getFixedOrderPsTime();
                isUpdate = true;
            }

            if (ValidateUtil.isAbsDouble(info.getWithPsKmInRang())) {
                orderOverTime += ", withPsKmInRang =" + info.getWithPsKmInRang();
                isUpdate = true;
            }

            if (info.getOutOneKmTime() != null) {
                orderOverTime += ", outOneKmTime =" + info.getOutOneKmTime();
                isUpdate = true;
            }
            String alertOrderTime = "";
            if (ValidateUtil.isAbsInteger(info.getAlertOrderTime())) {
                alertOrderTime = ", alertOrderTime =" + info.getAlertOrderTime();
            }
            String postmanAdvanceTime = "";
            if (ValidateUtil.isAbsInteger(info.getPostmanAdvanceTime())) {
                postmanAdvanceTime = ",postmanAdvanceTime=" + info.getPostmanAdvanceTime();
                isUpdate = true;
            }
            String notTakenOrderTime = "";
            if (ValidateUtil.isAbsInteger(info.getNotTakenOrderTime())) {
                notTakenOrderTime = ",notTakenOrderTime=" + info.getNotTakenOrderTime();
                isUpdate = true;
            }
            String shopNotSureTime = "";
            if (ValidateUtil.isAbsInteger(info.getShopNotSureTime())) {
                shopNotSureTime = ",shopNotSureTime=" + info.getShopNotSureTime();
                isUpdate = true;
            }
            String shopReadyTime = "";
            if (ValidateUtil.isAbsInteger(info.getShopReadyTime())) {
                shopReadyTime = ",shopReadyTime=" + info.getShopReadyTime();
                isUpdate = true;
            }
            String alertShopReadyTime = "";
            if (ValidateUtil.isAbsInteger(info.getAlertShopReadyTime())) {
                alertShopReadyTime = ",alertShopReadyTime=" + info.getAlertShopReadyTime();
                isUpdate = true;
            }

            // 配送单时长
            String postmanBackOrderTime = "";
            if (ValidateUtil.isAbsInteger(info.getPostmanBackOrderTime())) {
                postmanBackOrderTime = ",postmanBackOrderTime=" + info.getPostmanBackOrderTime();
                isUpdate = true;
            }

            // 预约单配置
            String appointPostmanTime = "";
            if (ValidateUtil.isAbsInteger(info.getAppointPostmanTime())) {
                appointPostmanTime = ",appointPostmanTime=" + info.getAppointPostmanTime();
                isUpdate = true;
            }
            String appointShopTime = "";
            if (ValidateUtil.isAbsInteger(info.getAppointShopTime())) {
                appointShopTime = ",appointShopTime=" + info.getAppointShopTime();
                isUpdate = true;
            }
            String appointShopAlertTime = "";
            if (ValidateUtil.isAbsInteger(info.getAppointShopAlertTime())) {
                appointShopAlertTime = ",appointShopAlertTime=" + info.getAppointShopAlertTime();
                isUpdate = true;
            }

            // 骑手抢单设置
            String postmanCanChangeCountPreDay = "";
            if (ValidateUtil.isAbsInteger(info.getPostmanCanChangeCountPreDay()) || info.getPostmanCanChangeCountPreDay() == -1) {
                postmanCanChangeCountPreDay = ",postmanCanChangeCountPreDay=" + info.getPostmanCanChangeCountPreDay();
                isUpdate = true;
            }
            String postmanMaxOrderNum = "";
            if (ValidateUtil.isAbsInteger(info.getPostmanMaxOrderNum()) || info.getPostmanMaxOrderNum() == -1) {
                postmanMaxOrderNum = ",postmanMaxOrderNum=" + info.getPostmanMaxOrderNum();
                isUpdate = true;
            }
            String postmanCanGrabOrder = "";
            if (ValidateUtil.isAbsInteger(info.getPostmanCanGrabOrder()) || info.getPostmanCanGrabOrder() == -1) {
                postmanCanGrabOrder = ",postmanCanGrabOrder=" + info.getPostmanCanGrabOrder();
                isUpdate = true;
            }

            // 多久后是预约单
            String isAppointTime = "";
            if (ValidateUtil.isAbsInteger(info.getIsAppointTime())) {
                isAppointTime = ",isAppointTime=" + info.getIsAppointTime();
                isUpdate = true;
            }

            // Jahnke 2020年11月20日 09:39:03
            String deliverType = "";
            if (StringUtils.isEmpty(info.getDeliveryType())) {
                info.setDeliveryType("sys");        // 默认非第三方配送
            }
            deliverType = ",deliveryType='" + info.getDeliveryType() + "'";

            sql.append("update ").append(PojoTables.AGENT_ORDER_OVERTIME).append(" set ")
                    .append(" updateUser = '").append(user.getUsername()).append("'")
                    .append(postmanOverTime)
                    .append(alertPostmanTime)
                    .append(shopOverTime)
                    .append(alertShopTime)
                    .append(orderOverTime)
                    .append(alertOrderTime)
                    .append(postmanAdvanceTime)
                    .append(notTakenOrderTime)
                    .append(postmanBackOrderTime)
                    .append(isAppointTime)
                    .append(shopNotSureTime).append(shopReadyTime).append(alertShopReadyTime)
                    .append(appointPostmanTime).append(appointShopTime).append(appointShopAlertTime)
                    .append(postmanCanChangeCountPreDay).append(postmanMaxOrderNum).append(postmanCanGrabOrder)
                    .append(isOpen)
                    .append(deliverType)
                    .append(",delFlag = ").append(info.getDelFlag()).append(" where id =").append(infoDB.getId());
            if (isUpdate) {
                try {
                    UserDaoSql.getInstance().executeBySql(sql.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    return AjaxResult.errorResult("更新失败，请稍后重试");
                }
                AgentOrderOverTimeMemory.getInstance().modify(infoDB.getAgentId());
            }
        }
        return AjaxResult.successResult();
    }
}
